<template>
  <div class="app-container">
    <PageSearch :showSearch.sync="showSearch" :getList="getList" :handleQuery="handleQuery" :resetQuery="resetQuery">
      <template #pagination>
        <pagination
          v-show="pageTotal > 0"
          :total="pageTotal"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </template>
      <template #form>
        <el-form :model="queryParams" ref="queryForm" size="small">
          <el-row>
            <el-form-item prop="timeBetween">
              <el-date-picker
                @change="getList"
                :placeholder="$t('时间选择')"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                v-model="queryParams.time"
                :start-placeholder="$t('开始时间')"
                :end-placeholder="$t('结束时间')"
                type="datetimerange"
              >
              </el-date-picker>
            </el-form-item>
            <!-- 账单类型 -->
            <el-form-item prop="type">
              <el-select
                :placeholder="$t('账单类型')"
                filterable
                clearable
                v-model="queryParams.type"
                @change="handleQuery"
              >
                <el-option
                  v-for="item in bill_type_platform_list"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                  :key="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item prop="type">
              <el-select
                :placeholder="$t('变动类型')"
                filterable
                clearable
                v-model="queryParams.changeType"
                @change="handleQuery"
              >
                <el-option :label="$t('增加')" :value="1" />
                <el-option :label="$t('减少')" :value="2" />
              </el-select>
            </el-form-item>
          </el-row>
        </el-form>
      </template>
      <template #actions>
        <div>
          平台余额:
          <span style="font-weight: bold; font-size: 20px; margin-right: 10px">{{ (+balance).toFixed() }}</span>
        </div>

        <el-button
          type="primary"
          @click="handleExport"
          v-hasPermi="['distribution:billPlatform:export']"
          plain
          size="mini"
        >
          时间范围导出
        </el-button>
        <el-button
          type="primary"
          v-hasPermi="['distribution:fundsPlatform:duty']"
          @click="handleReduce('1', '消费税扣减（余额日元1：1）')"
          plain
          size="mini"
        >
          消费税扣减
        </el-button>
        <el-button
          v-hasPermi="['distribution:fundsPlatform:freight']"
          type="primary"
          @click="handleReduce('2', '运费扣减（余额日元1：1）')"
          plain
          size="mini"
        >
          运费扣减
        </el-button>
        <el-button
          type="primary"
          v-hasPermi="['distribution:fundsPlatform:addSub']"
          @click="handleReduce('auto', '自由增减（余额日元1：1）')"
          plain
          size="mini"
        >
          自由增减
        </el-button>
      </template>
    </PageSearch>

    <el-row>
      <el-col :span="1.5">
        <!-- <div>平台账单记录</div> -->
      </el-col>
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" /> -->
    </el-row>
    <el-table :height="calTableHeight()" v-loading="loading" ref="TableRef" :data="tableData" row-key="menuId">
      <el-table-column align="center" show-overflow-tooltip prop="type" :label="$t('账单类型')">
        <template slot-scope="{ row }">
          <span :style="{ color: $randomColor(row.type) }">{{ handleType(row.type) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip prop="payAmount" :label="$t('变动金额')">
        <template slot-scope="{ row }">
          <div>{{ row.payAmount | thousand }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip prop="changeType" :label="$t('变动类型')">
        <template slot-scope="{ row }">
          <span v-if="row.changeType == 1">增加</span>
          <span v-if="row.changeType == 2">减少</span>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip prop="beforeFunds" :label="$t('变化前资金')">
        <template slot-scope="{ row }">
          <div>{{ row.beforeFunds | thousand }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip prop="afterFunds" :label="$t('变化后资金')">
        <template slot-scope="{ row }">
          <div>{{ row.afterFunds | thousand }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip prop="createTime" :label="$t('创建时间')" />
      <el-table-column align="center" show-overflow-tooltip prop="remark" :label="$t('备注')" />
      <!-- 操作 -->
      <el-table-column align="center" fixed="right" :label="$t('操作')" :width="calWidth(200, 250, 200)">
        <template slot-scope="{ row }">
          <el-button
            v-hasPermi="['distribution:billPlatform:query']"
            type="text"
            size="small"
            @click="handleDetail(row)"
          >
            <!-- 查看 -->
            {{ $t('查看') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="pageTotal > 0"
      :total="pageTotal"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <Reduce :type="reduce.type" @getList="getList(true)" :show.sync="reduce.show" :title="reduce.title" :data="reduce.data" />
    <Detail
      :FormData="FormData"
      :type="detailInfo.type"
      :show.sync="detailInfo.show"
      :title="detailInfo.title"
      :data="detailInfo.data"
    />
  </div>
</template>

<script>
import { billPlatform } from '@/api/bill/platform'
import { list, _export, balance } from '@/api/bill/platformBalance'
import { useDict } from '@/utils/useDict'
import Reduce from './components/reduce.vue'
import Detail from './components/detail.vue'
export default {
  activated() {
    this.$nextTick(() => this.$refs['TableRef']?.doLayout())
  },
  name: 'Platform',
  components: {
    Reduce,
    Detail,
  },
  data() {
    return {
      /**详情信息 */
      detailInfo: {
        /**显示详情 */
        show: false,
        type: '',
        title: '',
        data: [],
        query: {},
      },
      FormData: {},
      /**平台余额 */
      balance: '',
      showSearch: false,
      /**导出 */
      exportInfo: {},

      /**详情信息 */
      reduce: {
        /**显示详情 */
        show: false,
        type: '',
        title: '',
        data: [],
        query: {},
      },

      /**
       * 账单类型
       */
      bill_type_platform_list: [],
      tableData: [],
      /**数据总条数 */
      pageTotal: 0,
      loading: false,
      // 查询参数
      queryParams: {
        time: [],
        pageNum: 1,
        pageSize: 20,
        type: '',
        changeType: '',
      },
    }
  },
  created() {
    this.getList(true)
    useDict('bill_type_platform').then(({ bill_type_platform }) => {
      this.bill_type_platform_list = bill_type_platform
    })
  },
  methods: {
    handlePayType(type) {
      const index = this.bill_type_platform_list.findIndex((i) => i.dictValue == type)
      if (index > -1) return this.bill_type_platform_list[index].dictLabel
    },
    handleDetail(row) {
      const { id, type, typeId } = row
      billPlatform(id).then((res) => {
        const { code, data } = res
        this.FormData = data
        if (code === 200) {
          this.detailInfo.show = true
          this.detailInfo.title = this.handlePayType(type)
          this.detailInfo.type = type
          this.detailInfo.data = []

          switch (type) {
            case 1 /**.盘点亏款 type=1 */:
              this.detailInfo.data = data.lossStockCheckData
              break
            case 6 /**盘点收款 type=6 */:
              this.detailInfo.data = data.profitStockCheckData
              break

            case 7 /**提前付账单校服税 type=7 */:
              this.detailInfo.data = [data.beforeBillDuty]
              break
            case 8 /**阶段付款账单 type=8 */:
              this.detailInfo.data = data.phaseBillData
              break
            case 10 /**退货消费税返还给卖家 type=10 */:
              this.detailInfo.data = data.returnSkuDutyToSeller
              break
            case 11 /**.退货sku费用承担（供应商部分） type=11 */:
              this.detailInfo.data = data.returnSkuFeeToSeller
              break
            case 13 /**再发货sku费用承单 type=13 */:
              this.detailInfo.data = [data.reissueSkuFeeUnderTake]
              break
            case 21 /**  type=21 */:
              this.detailInfo.data = [data.orderChargeInfo]
              break
            case 22 /**退货运费捆包承担 type=22 */:
              this.detailInfo.data = [data.returnSkuFreightBaleFeeToSeller]
              break
            case 23 /**23.再发货运费捆包费收取 type=23 */:
              this.detailInfo.data = [data.reissueSkuFreightBaleFeeProfit]
              break
            case 24 /**24.再发货运费捆包费承担 type=24 */:
              this.detailInfo.data = [data.reissueSkuFreightBaleFeeUnderTake]
              break
            case 26 /**26.回收sku扣款 type=26 */:
              this.detailInfo.data = data.skuSellerRecoveryList
              break
            case 28 /**28充值 type=28 */:
              this.detailInfo.data = [data.sellerChargeInfo]
              let rechargeRecord = JSON.parse(data.sellerChargeInfo.remark)
              rechargeRecord.payAmount = data.sellerChargeInfo.payAmount
              this.detailInfo.data = [rechargeRecord]
              break
            case 31 /**代做模板付款 type=31 */:
              this.detailInfo.data = data.tempProxyApplyVoList
              break
            case 32 /**报废补偿扣减 type=32 */:
              this.detailInfo.data = [data.billPlatformScrapDetails]
              break
            case 33 /**删除包裹 type=33 */:
              this.detailInfo.data = [data.cancelOrderPackageVo]
              break
            default:
              break
          }
        }
      })
    },
    getBalance() {
      balance().then((res) => {
        const { code, data, msg } = res
        if (code === 200) {
          this.balance = data
        }
      })
    },
    handleExport() {
      if (this.queryParams.time.length == 0) {
        return this.$message({ type: 'error', message: this.$t('请选择时间范围') })
      }
      const data = {
        startTime: this.queryParams.time[0],
        endTime: this.queryParams.time[1],
      }
      this.download(
        'distribution/billPlatform/export',
        {
          ...this.queryParams,
          ...data,
        },
        `platformBalance_${new Date().getTime()}.xlsx`,
      )
    },
    handleType(type) {
      const index = this.bill_type_platform_list.findIndex((i) => i.dictValue == type)
      return this.bill_type_platform_list[index]?.dictLabel
    },
    handleReduce(type = '', title = '') {
      this.reduce.show = true
      this.reduce.type = type
      this.reduce.title = title
    },

    /** 查询菜单列表 */
    getList(getBalance = false) {
      if (getBalance) this.getBalance()
      /****************** 处理查询条件 *********************/
      const selectDate = this.queryParams.time || []
      const startTime = selectDate[0] || ''
      const endTime = selectDate[1] || ''
      const data = {
        ...this.queryParams,
        startTime,
        endTime,
      }
      delete data.time
      /**************** 处理查询条件 end *******************/
      this.loading = true
      list(data).then((res) => {
        this.tableData = res.rows
        this.pageTotal = res.total
        this.loading = false
      })
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 20
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      Object.keys(this.queryParams).forEach((key) => (this.queryParams[key] = ''))
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 20
      this.getList()
    },
  },
}
</script>
<style lang="scss"></style>
